package com.zyx.netty.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zyx.service.ResponseMsgService;
import com.zyx.service.ResponseMsgServiceResolver;
import com.zyx.vo.NettyHttpRequest;
import com.zyx.vo.NettyHttpResponse;
import io.netty.channel.*;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.Promise;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Map;

import static com.zyx.constants.Constants.DEVICE_RESPONSE;
import static com.zyx.constants.Constants.DEVICE_RESPONSE_URL;

/**
 * 描述说明:
 *
 * @author DQing
 * @version 1.0
 * @className DownControlHandler
 * @date 2020/3/25 18:09
 */
@Slf4j
@ChannelHandler.Sharable
@Component
public class DeviceResponseHandler extends SimpleChannelInboundHandler<FullHttpResponse> {

    @Autowired
    private ResponseMsgServiceResolver responseMsgServiceResolver;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception {

        String jsonStr = msg.content().toString(CharsetUtil.UTF_8);
        log.info("接收的响应报文内容content={}",jsonStr);
        JSONObject obj = JSON.parseObject(jsonStr).getJSONObject(DEVICE_RESPONSE);
        Map<String, Object> jsonMap = JSONObject.toJavaObject(obj, Map.class);
        String responseURL = (String) jsonMap.get(DEVICE_RESPONSE_URL);
        if(!StringUtils.isEmpty(responseURL)){
            ResponseMsgService responseMsgService = responseMsgServiceResolver.getResponseMsgService(responseURL);
            if(!StringUtils.isEmpty(responseMsgService)){
                responseMsgService.parseMsg(ctx,jsonMap);
            }
        }

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        log.info(cause.getMessage());
        cause.printStackTrace();
    }

}
